package middle.id_101_200;

// 5.22写
public class Lee151 {
    public static void main(String[] args) {
        String s = "a good   example";
        System.out.println(reverseWords2(s));
    }

    static public String reverseWords(String s) {    //新建了一个新的字符串，空间复杂度较高
        s = s.trim();
        String result = "";
        int right = s.length();
        int index = s.length() - 1;
        for (int i = s.length() - 1; i >= 0; i--) {
            if (i - 1 >= 0 && s.charAt(i - 1) == ' ' && s.charAt(i) != ' ') {
                result += s.substring(i, right).trim();
                result += " ";
                right = i - 1;
            } else if (i == 0 && s.charAt(i) != ' ') {
                result += s.substring(i, right).trim();
                result += " ";
            }
        }
        return result.trim();
    }

    static public String reverseWords2(String s) {  // 先反转整体，再反转每个单词(没写完)
        s = s.trim();
        char[] sArray = s.toCharArray();
        int cur = 0;
        for (int i = 0; i < sArray.length; i++) {
            if (sArray[i] != ' ') {
                sArray[cur] = sArray[i];
                cur++;
            } else if (sArray[i - 1] != ' ') {
                sArray[cur] = sArray[i];
                cur++;
            }
        }
        s=new String(sArray);

        return s;
    }
}
